<template>
    <div class="boxs">
        <el-card>
            <el-form :model="queryParams" ref="queryForm" :inline="true">
                <!-- <el-form-item :label="$t('feedback.ProjectName')">
                    <el-select v-model="queryParams.package_name" @change="handleQuery">
                        <el-option v-for="item in pkList" :key="item.package_name" :label="item.shortName"
                            :value="item.package_name"></el-option>
                    </el-select>
                </el-form-item> -->
                <!-- <el-form-item :label="$t('feedback.status')">
                    <el-select v-model="queryParams.state" @change="handleQuery">
                        <el-option v-for="item in stateList" :key="item.id" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item> -->
                <el-form-item :label="$t('feedback.installationtime')">
                    <el-date-picker v-model="value1" value-format="yyyy-MM-dd" type="daterange" range-separator="-"
                        :start-placeholder="$t('table.start')" :end-placeholder="$t('table.end')" @change="timeChange">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="small"
                        @click="handleQuery">{{ $t('table.search') }}</el-button>
                    <el-button icon="el-icon-refresh" size="small"
                        @click="resetQuery">{{ $t('table.reset') }}</el-button>
                </el-form-item>
            </el-form>
            <!-- <div class="flex_between">
        <span>{{$t('feedback.FeedbackManagement')}}</span>
      </div> -->
            <div class="statistics-container">
                <div class="item" v-for="(item, k) in statisticsList" :key="k">
                    {{ item.brand }}: {{ item.occurrences }} ({{ item.percentage }}%)
                </div>
            </div>
            <div class="flex_between">
                <div></div>
                <el-button type="warning" icon="el-icon-download" size="small"
                    @click="handleExport">{{ $t('table.export') }}</el-button>
            </div>
            <el-table border :data="moreArr" style="margin-top: 15px" v-loading="loading">
                <el-table-column label="index" align="center" width="60" type="index" />
                <el-table-column :label="$t('feedback.ProjectName')" align="center" prop="shortName" />
                <el-table-column :label="$t('feedback.brand')" align="center" prop="brand" />
                <el-table-column :label="$t('feedback.country')" align="center" prop="country" />

                <el-table-column :label="$t('feedback.tvModel')" align="center" prop="model" />
                <el-table-column :label="$t('feedback.installationtime')" align="center" width="180"
                    prop="first_install_time" />
                <el-table-column :label="$t('feedback.Submissiontime')" align="center" width="180" prop="create_date" />

                <el-table-column :label="$t('feedback.operate')" align="center" width="100">
                    <template slot-scope="scope">
                        <el-button size="mini"
                            @click="handleEdit(scope.$index, scope.row)">{{ $t('feedback.Check') }}</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.size"
                @pagination="getMore" />
            <div class="police-count1"></div>

        </el-card>

        <el-dialog :title="$t('feedback.operate')" :visible.sync="dialogVisible" width="800px">
            <el-form class="demo-form-inline" label-width="140px" :model="form" :rules="rules" ref="ruleForm">
                <el-row>
                    <el-col :span="12">
                        <el-form-item :label="$t('feedback.brand')" prop="brand">
                            <el-input disabled v-model="form.brand" placeholder="" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('feedback.country')" prop="country">
                            <el-input disabled v-model="form.country" placeholder="" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('feedback.tvModel')" prop="name">
                            <el-input disabled v-model="form.model" placeholder="" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="ip">
                            <el-input disabled v-model="form.ip" placeholder="" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('feedback.PackageName')" prop="name">
                            <el-input disabled v-model="form.package_name" placeholder="" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('feedback.DeviceLanguage')">
                            <el-input disabled v-model="form.lang" placeholder="" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('feedback.SDK')">
                            <el-input disabled v-model="form.sdk" placeholder="" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item :label="$t('feedback.installationtime')" prop="name">
                            <el-input disabled v-model="form.first_install_time" placeholder="" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('feedback.Operator')">
                            <el-input disabled v-model="form.operator" placeholder="" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('feedback.NetworkType')" prop="name">
                            <el-input disabled v-model="form.network_type" placeholder="" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">{{ $t('tagsView.close') }}</el-button>
                <!-- <el-button type="warning" @click="affirm">{{ $t('table.confirm') }}</el-button> -->
            </div>
        </el-dialog>
    </div>
</template> 
<script>
import { getFeedback, getPkList, editFeedbackState, getDataListAll, statistics } from "@/api/brand";
import { getLanguage, gptTranslate } from "@/api/appComment";
import pk from "@/utils/pk";
import * as XLSX from "xlsx";

export default { 
    name: "brand",
    data() {
        return {
            languageContent: '',
            goalLanguage: "zh_CN",
            languageList: [],
            translateLoading: false,
            pkList: [],
            stateList: [
                {
                    id: "0",
                    name: "未处理",
                },
                {
                    id: "1",
                    name: "已处理",
                },
            ],
            queryParams: {
                page: 1,
                size: 10,
                dateRange: {
                    start: "",
                    end: "",
                },
                state: "",
                package_name: "",
            },
            total: 0,
            loading: false,
            addLoading: false,
            moreArr: [],
            dialogVisible: false,
            form: {
                comment_type: "",
            },
            search: "",
            rules: {
                comment_type: [
                    { required: true, message: "请输入类型", trigger: "blur" },
                ],
            },
            value1: "",
            statisticsList: [],
            chartContainer1: null,
            option1: {},
            chartData:[]
        };
    },
    created() {
        this.getMore();
        this.getPkListHandel();
        this.getLanguageList();
        this.getStatistics();
    },
    mounted() {

    },
    methods: {
        async getStatistics() {
            let { data } = await statistics(this.queryParams);
            this.chartData = data;
            this.option1 = {
                color: ['#3489FF'],
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '22%'
                },
                xAxis: [{
                    type: 'category',
                    data: this.chartData.map(item => item.brand), // 从 chartData 中获取品牌
                    axisLine: { show: false },
                    axisTick: { show: false },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13,
                        interval: 0,
                        rotate: 45
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                yAxis: [{
                    type: 'value',
                    axisLine: { show: false },
                    axisTick: { show: false },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                series: [{
                    data: this.chartData.map(item => item.occurrences), // 从 chartData 中获取数量
                    type: 'bar',
                }],
                tooltip: {
                    trigger: 'axis',
                    backgroundColor: 'rgba(32, 33, 36,.7)',
                    borderColor: 'rgba(32, 33, 36,0.20)',
                    borderWidth: 1,
                    textStyle: {
                        color: '#fff',
                        fontSize: '12'
                    },
                    axisPointer: {
                        type: 'shadow',
                        label: {
                            backgroundColor: '#6a7985'
                        }
                    },
                    formatter: (params) => {
                        const dataIndex = params[0].dataIndex;
                        const brand = this.chartData[dataIndex].brand;
                        const occurrences = this.chartData[dataIndex].occurrences;
                        const percentage = this.chartData[dataIndex].percentage;
                        return `
                            品牌: ${brand}<br>
                            数量: ${occurrences}<br>
                            百分比: ${percentage}%
                        `;
                    }
                },
                dataZoom: {
                    type: 'inside'
                }
            };
            this.initChart1()


            this.statisticsList = data

        },
        timeChange() {
            this.queryParams.dateRange.start = this.value1[0];
            this.queryParams.dateRange.end = this.value1[1];
            this.handleQuery();
        },
        getKeyByValue(object, value) {
            return Object.keys(object).find((key) => object[key] === value);
        },
        async getMore() {
            this.loading = true;
            let { data, total } = await getFeedback(this.queryParams);
            if (data.length != 0) {
                data.forEach((item) => {
                    if (item.files) {
                        let filesArray = item.files.split("|");

                        // 检查数组第一项是否以竖线开头
                        if (filesArray[0] === "") {
                            filesArray.shift(); // 移除第一个空字符串项
                        }

                        item.files = filesArray;
                    }
                    if (item.videoUrl) {
                        item.videoUrl = item.videoUrl.split("|");
                    }
                });
            }
            this.loading = false;
            this.moreArr = data;
            this.total = total;
        },
        async getLanguageList() {
            let { data } = await getLanguage({
                package_name: this.queryParams.package_name,
            });
            this.languageList = data.map((item) => ({
                id: item.reviewer_language,
                name: item.reviewer_language,
            }));
        },
        async translateHandel() {
            this.languageContent = "";
            this.translateLoading = true;
            let { data } = await gptTranslate({
                language: this.goalLanguage,
                translateText: this.form.description,
            });
            this.translateLoading = false;
            if (data.code == 0) {
                this.languageContent = data.data.answer;
            }
        },
        async getPkListHandel() {
            let { data } = await getPkList({ page: 1, size: 999 });
            this.pkList = data;
        },
        handleQuery() {
            this.queryParams.page = 1;
            this.getMore();
        },
        async affirm() {
            this.form.package_name = this.queryParams.package_name;
            this.$refs["ruleForm"].validate(async (valid) => {
                if (!valid) return;
                try {
                    this.addLoading = true;
                    await editFeedbackState(this.form);
                    this.addLoading = false;
                    this.$message.success("操作成功");
                    this.getMore();
                    this.dialogVisible = false;
                } catch (e) {
                    this.addLoading = false;
                }
            });
        },
        openDialog() {
            this.form = {};
            this.dialogVisible = true;
        },
        handleEdit(i, row) {
            this.languageContent = ''
            this.form = { ...row };
            this.dialogVisible = true;
        },
        handleDelete(index, row) {
            this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "error",
            }).then(async () => {
                await deleteTemplateType({ id: row.id });
                this.getMore();
                this.$message({
                    message: "删除成功！",
                    type: "success",
                });
            });
        },
        resetQuery() {
            this.queryParams.state = null;
            this.queryParams.package_name = null;
            this.queryParams.dateRange.start = null;
            this.queryParams.dateRange.end = null;
            this.queryParams.page = 1;
            this.value1 = "";
            this.getMore();
        },
        async handleExport() {
            this.loading = true;
            let { data } = await getDataListAll(this.queryParams);
            const ws = XLSX.utils.json_to_sheet(data); // 将JSON转换成sheet
            const wb = XLSX.utils.book_new(); // 新建workbook
            XLSX.utils.book_append_sheet(wb, ws, "Sheet1"); // 在workbook中添加新的sheet
            XLSX.writeFile(wb, "MySpreadsheet.xlsx"); // 写文件并触发下载
            this.loading = false;
        },
        initChart1() {
            this.chartContainer1 = this.$echarts.init(document.querySelector('.police-count1'))
            this.chartContainer1.setOption(this.option1)
        },
    },
};
</script>
<style lang="scss" scoped>
.boxs {
    padding: 20px;
}

::v-deep.el-input.is-disabled .el-input__inner {
    color: #333 !important;
}

::v-deep.el-textarea.is-disabled .el-textarea__inner {
    color: #333 !important;
}

::v-deep .el-image {
    margin-right: 8px;
    border-radius: 4px;
}

.statistics-container {
    display: flex;
    flex-wrap: wrap;
    /* 自动换行 */
    gap: 10px;
    /* 数据块之间的间距 */
    padding: 10px;
    border: 1px solid #ddd;
    margin-bottom: 20px;
    font-size: 14px;
}

.item {
    background-color: #f9f9f9;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    display: inline-block;
    /* 使得每个元素成为一块 */
    white-space: nowrap;
    /* 防止单个元素中的文本换行 */
}

.police-count1 {
    margin-top: -30px;
    width: 100%;
    min-width: 1000px;
    height: 400px;
    color: #000;
    padding-bottom: 30px;
}
</style>